/*
 * @Author: taoyuqing
 * @Date: 2022-12-29 01:20:30
 * @Description: 消息页面
 */
import 'dart:convert';

import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:provider/provider.dart';
import 'package:spree/utils/resp_code_enum.dart';
import 'package:spree/utils/utils.dart';
import 'package:spree/widgets/common_container.dart';
import 'package:flutter_slidable/flutter_slidable.dart';

import '../provider/model/user_model.dart';
import '../utils/api.dart';
import 'message/message_detail.dart';

class MessagePage extends StatefulWidget {
  MessagePage({Key? key}) : super(key: key);

  @override
  State<MessagePage> createState() => _MessagePageState();
}

class _MessagePageState extends State<MessagePage>
    with AutomaticKeepAliveClientMixin {
  List _items = [];

  @override
  void initState() {
    // TODO: implement initState
    String? userId = context.read<UserModel>().userId;
    if (userId != '') {
      listMessage();
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('Message'),
      ),
      body: CommonContainer(
        width: Utils().getScreenWidth(context),
        child: _items.isEmpty
            ? Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset(
                    'images/no-message.png',
                    width: 200,
                  ),
                  Text(
                    'No Messages Available',
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                        fontWeight: FontWeight.w700),
                  )
                ],
              )
            : ListView.separated(
                padding: EdgeInsets.only(top: 20),
                separatorBuilder: (BuildContext context, int index) =>
                    Divider(height: 1.0, color: Colors.white30),
                itemCount: _items.length,
                itemBuilder: (context, index) {
                  return _slidableWidget(index, _items[index]);
                },
              ),
      ),
    );
  }

  listMessage() async {
    _items = [];
    Map param = {
      'page': {'pageNo': 1, 'pageSize': 20}
    };
    dynamic temp = await Api.listMessage(param);
    if (temp['code'] == RespCode.SUCCESS.code) {
      List result = temp['data'];
      for (int i = 0; i < result.length; i++) {
        _items.add(result[i]);
      }
      print(_items);
      setState(() {});
    }
  }

  readMessage(id) async {
    Map param = {"id": id};
    dynamic temp = await Api.readMessage(param);
    listMessage();
  }

  Widget _drawerDivider() {
    return Container(
      margin: EdgeInsets.only(top: 15, bottom: 15),
      child: const Divider(
        height: 1,
        color: Color(0xFF8B8AD1),
      ),
    );
  }

  Widget _listViewItem(item) {
    return Container(
      padding: EdgeInsets.only(top: 10, bottom: 10),
      decoration: BoxDecoration(
        color: Color(0xff2C1F76),
      ),
      child: ListTile(
        leading: Badge(
          showBadge: !item['isRead'],
          position: BadgePosition(top: -4, end: -4),
          child: Image.asset(
            'images/avatar.jpg',
            width: 50,
            height: 50,
          ),
        ),
        title: Text(
          item['msgTypeName'],
          style: TextStyle(color: Colors.white),
        ),
        subtitle: Container(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                item['content'],
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(fontSize: 16, color: Colors.white),
              ),
              Text(item['createdAt'],
                  style: TextStyle(color: Color(0xffB0AFEC)))
            ],
          ),
        ),
      ),
    );
  }

  Widget _slidableWidget(index, item) {
    return Slidable(
      key: ValueKey("$index"),
      endActionPane: ActionPane(motion: ScrollMotion(), children: [
        SlidableAction(
          onPressed: (context) {
            setState(() {
              _items.removeAt(index);
            });
          },
          backgroundColor: Colors.red,
          icon: Icons.delete,
          label: 'delete',
        ),
      ]),
      child: GestureDetector(
        onTap: () {
          // Navigator.pushNamed(context, 'MessageDetail',arguments: {
          //   "title":"消息标题",
          //   "content":"消息内容"
          // });
          print(item);
          readMessage(item['id']);
          Navigator.push(context, MaterialPageRoute(builder: (context) {
            return MessageDetail(
              msgTitle: item['msgTypeName'],
              msgContent: item['content'],
            );
          }));
        },
        child: _listViewItem(item),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
